<template>
    <div class="common_content">
        <Row>
            <Alert>
                产品贴息方案信息
            </Alert>
        </Row>
        <br>
        <Form ref="discountConfigForm" :model="discountConfigForm" :label-width="50" :rules="rules">
            <div class="basis-info">
            <Row>
                <Col :xs="24" :md="12" :lg="8" :xl="6" v-if="op!='add'">
                    <FormItem label="贴息编号" prop="discountNo" :label-width="100">
                        <Input v-model="discountConfigForm.discountNo" style="width: 150px" :disabled="readonly"/>
                    </FormItem>
                </Col>
                <Col :xs="24" :md="12" :lg="8" :xl="6">
                    <FormItem label="贴息方案名称" prop="discountPlanName" :label-width="100">
                        <Input v-model="discountConfigForm.discountPlanName" style="width: 150px" :disabled="readonlyOther"/>
                    </FormItem>
                </Col>
                <Col :xs="24" :md="12" :lg="8" :xl="6">
                    <FormItem label="贴息计算方式" prop="discountCalculateMethod" :label-width="100">
                        <Select v-model="discountConfigForm.discountCalculateMethod" style="width:150px" :disabled="readonlyOther" @on-change="discountCalculateMethodSelect">
                            <Option v-for="item in discountCalculateMethodList" :value="item.value" :key="item.value" :label="item.title">
                                {{item.title}}
                            </Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col :xs="24" :md="12" :lg="8" :xl="6">
                    <FormItem label="补贴分成方式" prop="discountShareMethod" :label-width="100">
                        <Select v-model="discountConfigForm.discountShareMethod" style="width:150px" :disabled="readonlyOne" @on-change="discountShareMethodSelect">
                            <Option v-for="item in discountShareMethodList" :value="item.value" :key="item.value" :label="item.title">
                                {{item.title}}
                            </Option>
                        </Select>
                    </FormItem>
                </Col>
            </Row>
            </div>
        </Form>
        <br>
        <Row>
            <Alert>
                补贴方信息
            </Alert>
        </Row>
        <Button @click="add" type="primary" v-show="isShow" icon="md-add">新增</Button>
        <div>
            <Table :loading="loading" highlight-row border  :columns="columns" :data="dataTable" sortable="custom" ref="table" @on-drag-drop="onDragDrop" :draggable="true">
                <template slot="subsidySide" slot-scope="{ row, index }">
                    <span>{{getSubsidySideList(row.subsidySide)}}</span>
                </template>
                <template slot="subsidyName" slot-scope="{ row, index }">
                    <span>{{getSubsidyNameList(row.subsidyName)}}</span>
                </template>
                <template slot="totalToTotal" slot-scope="{ row, index }">
                    <span>{{getTotalToTotalList(row.totalToTotal)}}</span>
                </template>
                <template slot="singleSelect" slot-scope="{ row, index }">
                    <span>{{getSingleSelectList(row.singleSelect)}}</span>
                </template>
                <template slot="subsidy" slot-scope="{ row, index }">
                    <span>{{getSelectDiscountRuleDataDetail(row)}}</span>
                </template>
                <template slot-scope="{ row, index }" slot="action">
                    <Button @click="dataTableEdit(row,index)" size="small" style="margin-right:5px" type="primary">编辑</Button>
                    <Button @click="dataTableRemove(row,index)" size="small" type="error">删除</Button>
                </template>
            </Table>
        </div>
        <br>
        <Row style="text-align: center;">
            <Button @click="save" type="primary" v-show="isShow" icon="md-bookmark">保存</Button>
            <Button @click="backPage" type="primary" icon="md-backspace">返回</Button>
        </Row>

        <Modal
            v-model="discountModalVisible"
            :title="modalTitle"
            :width="500"
            :closable="false"
            :mask-closable="false"
            @on-ok="discountSubmit"
        >

            <Form ref="subsidySideForm" :model="subsidySideForm" :label-width="150" :rules="rulesSubsidySide">
                <Row>
                    <Col span="24">
                        <FormItem label="补贴方" prop="subsidySide">
                            <Select v-model="subsidySideForm.subsidySide" style="width:200px"  @on-change="changeSubsidySide" >
                                <Option v-for="item in subsidySideList" :value="item.value" :key="item.value" :label="item.title">
                                    {{item.title}}
                                </Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="24" v-if="subsidySideForm.subsidySide=='0'">
                        <FormItem label="补贴方名称" prop="subsidyName">
                            <Select v-model="subsidySideForm.subsidyName" style="width:200px" >
                                <Option v-for="item in subsidyNameList" :value="item.value" :key="item.value" :label="item.title">
                                    {{item.title}}
                                </Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="是否总对总" prop="totalToTotal">
                            <Select v-model="subsidySideForm.totalToTotal" style="width:200px" >
                                <Option v-for="item in totalToTotalList" :value="item.value" :key="item.value" :label="item.title">
                                    {{item.title}}
                                </Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="24" v-if="discountConfigForm.discountShareMethod=='2'">
                        <FormItem label="补贴比例%" prop="subsidyRate">
                            <InputNumber :max="100" :min="0" v-model="subsidySideForm.subsidyRate" style="width: 200px" type="number"/>
                        </FormItem>
                    </Col>

                    <Col span="24">
                        <FormItem label="方案/金额" prop="singleSelect">
                            <Select v-model="subsidySideForm.singleSelect" style="width:200px"  @on-change="changeSingleSelect" clearable>
                                <Option v-for="item in singleSelectList" :value="item.value" :key="item.value" :label="item.title">
                                    {{item.title}}
                                </Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="24" v-if="subsidySideForm.singleSelect=='1'">
                        <FormItem label="最高补贴额" prop="subsidyMoney">
                            <InputNumber v-model="subsidySideForm.subsidyMoney" style="width: 200px" :min="0"/>
                        </FormItem>
                    </Col>
                    <Col span="24" v-if="subsidySideForm.singleSelect=='0'">
                        <FormItem label="最高补贴额" prop="discountRulePlanId">
                            <Select style="width: 200px" v-model="subsidySideForm.discountRulePlanId">
                                <Option v-for="item in subsidyMoneyRuleData" :value="item.value" :key="item.value">
                                    {{item.label }}
                                </Option>
                            </Select>
                        </FormItem>
                    </Col>


                </Row>
            </Form>

            <div style="margin-left:50%;" slot="footer">
                <Button size="small" @click="cancle">取消</Button>
                <Button type="primary" size="small" v-show="isShow"  @click="discountSubmit">保存</Button>
            </div>
        </Modal>

    </div>
</template>
<script>
    import {getByTypes} from "_p/basic/api/admin/datadic";
    import {deepClone} from "@/libs/utils/ObjectClone";
    import {
        getSelectDiscountRuleData,
        saveOrUpdateConfigByType,
        getDiscountConfigDataByPlanID
    } from "@/projects/afs-core-business/api/afs-product/product/discountConfig";

    export default {
        data() {
            return {
                op:null,
                readonly:true,
                readonlyOther:true,
                readonlyOne:true,
                discountCalculateMethodList:[],
                discountShareMethodList:[],
                subsidySideList:[],
                subsidyNameList:[],
                totalToTotalList:[],
                singleSelectList:[],
                subsidyMoneyRuleData: [],
                discountConfigForm:{
                    discountNo:null,
                    discountPlanName:null,
                    discountCalculateMethod:null,
                    discountShareMethod:null,
                },
                rules: {
                    discountNo: [ {required: true, message: " 不能为空",trigger: "blur"}],
                    discountPlanName: [ {required: true, message: " 不能为空",trigger: "blur"}],
                    discountCalculateMethod: [ {required: true, message: " 不能为空",trigger: "blur"}],
                    discountShareMethod: [ {required: true, message: " 不能为空",trigger: "blur"}],
                },
                columns: [
                    {
                        title: '补贴方',
                        key: 'subsidySide',
                        align: "center",
                        slot:"subsidySide",
                    },
                    {
                        title: '补贴方名称',
                        key: 'subsidyName',
                        align: "center",
                        slot:"subsidyName",
                    },
                    {
                        title: '补贴比例%',
                        key: 'subsidyRate',
                        align: "center",
                    },
                    {
                        title: '是否总对总',
                        key: 'totalToTotal',
                        align: "center",
                        slot:"totalToTotal",
                    },
                    {
                        title: '方案/金额',
                        key: 'singleSelect',
                        align: "center",
                        slot:"singleSelect",
                    },
                    {
                        title: '最高补贴额',
                        key: 'subsidy',
                        align: "center",
                        slot:"subsidy",
                    },
                    {
                        title: "操作",
                        key: "action",
                        align: "center",
                        fixed: "right",
                        slot: "action",
                    }
                ],
                dataTable: [
                    {
                        subsidySide:"0",
                        subsidyName:"0",
                        totalToTotal:"0",
                        subsidyRate:50,
                        singleSelect:"0",
                        subsidy:"4442447642494411492",
                    }
                ],//列表的值
                isShow:true,//新增按钮是否展示
                discountModalVisible:false,//弹窗是否展示
                modalTitle:"补贴方信息",
                subsidySideForm:{
                    subsidySide:null,
                    subsidyName:null,
                    totalToTotal:null,
                    subsidyRate:null,
                    singleSelect:null,
                    discountRulePlanId:null,
                    subsidyMoney:null,
                    discountSerialNumber:null,
                },
                rulesSubsidySide: {
                    subsidySide: [ {required: true, message: " 不能为空",trigger: "blur"}],
                    subsidyName: [ {required: true, message: " 不能为空",trigger: "blur"}],
                    totalToTotal: [ {required: true, message: " 不能为空",trigger: "blur"}],
                    subsidyRate: [ {required: true, message: " 不能为空",trigger: "blur",type:"number"}],
                    subsidyMoney: [ {required: true, message: " 不能为空",trigger: "blur",type:"number"}],
                    discountRulePlanId: [ {required: true, message: " 不能为空",trigger: "blur"}],
                },
                subsidyShow:true,//补贴方案/金额
                discountShareMethodShow:true,//补贴分成方式
                loading: false,
                discountSerialNumber:0,
                judgeSave:false,
                judgeIndex:null,
            };
        },
        props: {
            //状态
            op:{
                type:String,
                required: true,
                default: 'view'
            },
            //数据
            param:{
                type:Object,
            },
        },
        mounted() {
            this.getDiscountConfigInfo(this.op,this.param);
        },
        methods: {
            getDiscountConfigInfo(op,val) {

                //初始化数据
                this.initDatadic();
                this.selectDiscountRuleData();
                //初始化状态
                this.op=op;
                if(op=="add"){
                    //设定只读
                    this.isShow=true;
                    this.readonly=false;
                    this.readonlyOther = false;
                    this.readonlyOne = false;
                    //新增，清空数据
                    this.$refs['discountConfigForm'].resetFields();
                    this.dataTable = [];
                }else if(op=="edit"){
                    //设定只读
                    this.isShow=true;
                    this.readonly=true;
                    this.readonlyOther = false;
                    this.readonlyOne = false;
                    //带出数据
                    this.discountConfigForm = val;
                    this.discountConfigDatas(val.id);
                }else if(op=="view"){
                    //设定只读
                    this.isShow=false;
                    this.readonly=true;
                    this.readonlyOther = true;
                    this.readonlyOne = true;
                    this.columns.pop(); //移除数组的最后一项，返回移除的项
                    //带出数据
                    this.discountConfigForm = val;
                    this.discountConfigDatas(val.id);
                }
            },
            //查询补贴方列表值
            discountConfigDatas(id) {
                getDiscountConfigDataByPlanID(id).then(res => {
                    if (res.code === "0000") {
                        this.dataTable = res.data;
                    }else{
                        this.dataTable = [];
                    }
                });
            },
            //数据字典
            initDatadic() {
                //贴息计算方式/补贴分成方式/补贴方/是否总队总/选择(方案/金额)
                let arr = ["discountCalculationMethod", "discountShareMethod", "subsidySideType","whetherStatus","rulePlanSelect","subsidyNameType"];
                getByTypes(arr).then(res => {
                    if (res.code === "0000") {
                        // console.info(res.data);
                        this.discountCalculateMethodList=res.data.discountCalculationMethod;
                        this.discountShareMethodList=res.data.discountShareMethod;
                        this.subsidySideList=res.data.subsidySideType;
                        this.totalToTotalList=res.data.whetherStatus;
                        this.singleSelectList=res.data.rulePlanSelect;
                        this.subsidyNameList = res.data.subsidyNameType;
                    }
                });
            },
            //补贴方
            getSubsidySideList(val) {
                let dic = {}
                this.subsidySideList.forEach(column => {
                    if (column.value === val) {
                        dic = column;
                    }
                });
                return dic.title;
            },
            //补贴方名称
            getSubsidyNameList(val) {
                let dic = {}
                this.subsidyNameList.forEach(column => {
                    if (column.value === val) {
                        dic = column;
                    }
                });
                return dic.title;
            },
            //是否总对总
            getTotalToTotalList(val) {
                let dic = {}
                this.totalToTotalList.forEach(column => {
                    if (column.value === val) {
                        dic = column;
                    }
                });
                return dic.title;
            },
            //选择:方案/金额
            getSingleSelectList(val) {
                let dic = {}
                this.singleSelectList.forEach(column => {
                    if (column.value === val) {
                        dic = column;
                    }
                });
                return dic.title;
            },
            //最高补贴额方案
            selectDiscountRuleData() {
                getSelectDiscountRuleData().then(res => {
                    if (res.code === "0000") {
                        this.subsidyMoneyRuleData = res.data;
                        // console.info(this.subsidyMoneyRuleData);
                    }
                });
            },
            getSelectDiscountRuleDataDetail(val) {
                // console.info(val.singleSelect);
                if("0"==val.singleSelect){
                    let dic = {}
                    this.subsidyMoneyRuleData.forEach(column => {
                        console.info("最高补贴额度方案"+val.discountRulePlanId);
                        if (column.value === val.discountRulePlanId) {
                            dic = column;
                            console.info("最好补贴额度"+dic);
                        }
                    });
                    return dic.label;
                }else if("1"==val.singleSelect){
                    return val.subsidyMoney;
                }
            },
            //返回父页面
            backPage() {
                this.$emit('saveSuccess', "退回");
            },
            //新增补贴方
            add(){
                this.discountModalVisible=true;
                this.subsidySideForm={
                    subsidySide:null,
                    subsidyName:null,
                    totalToTotal:null,
                    subsidyRate:null,
                    singleSelect:null,
                    discountRulePlanId:null,
                    subsidyMoney:null,
                };
            },
            //修改补贴方
            dataTableEdit(row, index){
                // console.info("源的数据："+JSON.stringify(row));
                this.discountModalVisible=true;
                this.subsidySideForm = (deepClone(row));
                this.judgeIndex = index;
                this.judgeSave = true;
                // console.info("复制后的数据："+JSON.stringify(this.subsidySideForm));
            },
            //删除补贴方
            dataTableRemove(row, index){
                let self = this;
                self.$Modal.confirm({
                    title: "确认删除",
                    content: "您确认要删除?",
                    onOk: () => {
                        self.dataTable.splice(index, 1);
                    }
                });
            },
            cancle(){
                this.discountModalVisible = false;
                this.judgeSave = false;
            },
            //保存补贴方
            discountSubmit(){
                // console.info("保存的数据："+JSON.stringify(this.subsidySideForm));
                this.$refs['subsidySideForm'].validate((valid) => {
                    if (valid) {
                        //定位使用，方便页面数据移动
                        this.subsidySideForm.discountSerialNumber= this.discountSerialNumber;
                        this.discountSerialNumber = this.discountSerialNumber+1;
                        if(this.judgeSave){//编辑
                            //列表新增数据
                            this.dataTable.splice(this.judgeIndex,1,this.subsidySideForm);
                        }else{//保存
                            //列表新增数据
                            this.dataTable.push(this.subsidySideForm);
                        }
                        //关闭弹窗
                        this.discountModalVisible=false;
                        this.judgeSave = false;
                    } else {
                        return false;
                    }
                });
            },
            //边盖方案/金额选择时，清空最高补贴额金额
            changeSingleSelect(){
                this.subsidySideForm.subsidyMoney=0;
            },
            //补贴方选择时，清空补贴方名称
            changeSubsidySide(){
                this.subsidySideForm.subsidyName=null;
            },
            //保存当前页数据
            save() {
                this.$refs["discountConfigForm"].validate((valid) => {
                    if (valid) {
                        var subsidySideData=  this.dataTable;//补贴方数据
                        // console.info("保存时的数据列表："+this.dataTable+",第一条数据："+JSON.stringify(this.dataTable[0])+",长度："+this.dataTable.length);
                        // console.info("保存时的数据列表1："+subsidySideData+",第一条数据1："+JSON.stringify(subsidySideData[0])+",长度："+subsidySideData.length);
                        var discountConfigFormData = this.discountConfigForm;//方案数据
                        if(subsidySideData.length==0){
                            this.$Message.error('填写补贴方信息！');
                            return;
                        }
                        // console.info("保存时的数据长度："+subsidySideData+","+subsidySideData.length);
                        if(discountConfigFormData.discountShareMethod=="1"){//按顺序补贴
                            var endData = subsidySideData[subsidySideData.length-1];//获取数组最后一位数据
                            // console.info("最后一位数据："+endData);
                            // console.info("最后一位数据singleSelect："+endData.singleSelect);
                            if(endData.singleSelect!=null){
                                this.$Message.error('按顺序补贴时，最后一位不允许有最高补贴额!');
                                return;
                            }
                        }else if(discountConfigFormData.discountShareMethod=="2"){//按照比例补贴
                            var i=0;
                            var m =0;
                            subsidySideData.forEach(column => {
                                if (column.singleSelect !=null) {
                                    i++;
                                }
                                m=m+ parseFloat(column.subsidyRate);
                            });
                            // console.info("m"+m);
                            if(m!=100){
                                this.$Message.error('比例补贴时，比例必须为100！');
                                return;
                            }
                            if(i>1){
                                this.$Message.error('比例补贴时，最多只有1个最高补贴额!');
                                return;
                            }
                        }else{
                            this.$Message.error('补贴方不正确！');
                            return;
                        }
                        let param = {
                            productDiscountPlan:discountConfigFormData,
                            productDiscountSubsidyList:subsidySideData,
                            op:this.op,
                        }
                        saveOrUpdateConfigByType(param).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("保存成功！");
                                this.op = 'edit';
                                this.$emit('saveSuccess', "退回");
                            }
                        });
                    } else {
                        this.$Message.error('方案信息不完整!');
                    }
                })
            },
            onDragDrop(index1, index2) {
                // console.info(index1, index2);
                var listAtom = this.dataTable;
                // console.info(JSON.stringify(listAtom))
                listAtom[index1] = listAtom.splice(index2, 1, listAtom[index1])[0];
                // console.info(JSON.stringify(listAtom))
                this.dataTable = listAtom;
            },
            //补贴分成方式为顺序时，为顺序的时候清空比例值
            discountShareMethodSelect(){
                if(this.discountConfigForm.discountShareMethod=='1'){
                    for(var i=0;i<this.dataTable.length;i++){
                        this.dataTable[i].subsidyRate = null;
                    }
                }
            },
            //贴息计算方式为灵活贴息时，只能按照顺序
            discountCalculateMethodSelect(){
                if(this.discountConfigForm.discountCalculateMethod=='3'){
                    this.discountConfigForm.discountShareMethod='1';
                    this.readonlyOne = true;
                }else{
                    this.readonlyOne = false;
                }
            },
        },
    };
</script>

<style scoped>
    .common_content {
        background-color: white;
        padding: 16px;
    }
    .basis-info>>>.ivu-input[disabled]{
        color: black;
    }
    .basis-info>>>.ivu-select-disabled .ivu-select-selected-value{
        color:#515a6e;
    }
    .basis-info>>>.ivu-input-number-input[disabled]{
        color:black;
    }
</style>
